package survivial;

import java.util.EnumSet;
import java.util.List;
import java.util.Random;

import com.google.common.collect.Lists;

import survivial.Survivial;
import net.minecraft.block.Block;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraft.world.WorldManager;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;

public class SurvivialTickHandler implements ITickHandler
{
	private int _count;
	private int _count2;
	EnumSet<TickType> _ticks;
	
    private int[][] _offsets;
    
    private int lastX, lastY, lastZ;
    private int _beneathCount;
    private Random _rand;
    private List<TileEntityCampfire> _entitiesToUpdate;

	
	public SurvivialTickHandler()
	{
		_entitiesToUpdate = Lists.newArrayList();
        this._ticks = EnumSet.of(TickType.CLIENT);
        _rand = new Random();
	}
	
	public void RegisterEntity(TileEntityCampfire entity)
	{
		_entitiesToUpdate.add(entity);
	}
	
	private long _startTime = -1;
	private double _tickRate;
	private long _earliestTimeForNextUpdate;

	@Override
	public void tickStart(EnumSet<TickType> type, Object... tickData) 
	{
		if (true) //  (_count % 10) == 1)
		{	// Update System time every so often
			Survivial.SystemTime = Survivial.TheMineCraft.getSystemTime();
		}
		if (_startTime < 0)
		{
			_startTime = Survivial.SystemTime;
			_earliestTimeForNextUpdate = _startTime;
		}
		
		if (Survivial.SystemTime < _earliestTimeForNextUpdate)
			return; // too soon

		_count++;

		double runTime = (Survivial.SystemTime - _startTime) / 1000.0;
		if (runTime > 0)
		{
			_tickRate = _count / runTime;
		}

		_earliestTimeForNextUpdate += 100; // aiming for 10 Hz update rate, approx
		if (_earliestTimeForNextUpdate < Survivial.SystemTime)
			_earliestTimeForNextUpdate = Survivial.SystemTime;
		
		World world = Survivial.getWorld(); //  EventManager.World;
		if (world == null)
		{
			return; // too soon, world is not initialized yet
		}
		for(int i = 0; i < _entitiesToUpdate.size(); i++)
		{
			TileEntityCampfire e = _entitiesToUpdate.get(i);
			e.UpdateFlames();
		}
	}

	@Override
	public void tickEnd(EnumSet<TickType> type, Object... tickData) {
		// TODO Auto-generated method stub
		_count2++;
	}

	@Override
	public EnumSet<TickType> ticks() {
		// TODO Auto-generated method stub
		return _ticks;
	}

	@Override
	public String getLabel() {
		// TODO Auto-generated method stub
		return "TutorialTicks.Label";
	}

}
